﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using tuwien.auto.eibclient;

namespace KNXFramework.KNXObjects.ValueObjects
{
    public class SwitchingObjectValue : IValueObject
    {
        #region Fields

        private bool m_Value;

        public bool Value
        {
            get { return m_Value; }
            set { m_Value = value; }
        }

        #endregion

        #region Constructors
        public SwitchingObjectValue(bool value)
        {
            m_Value = value;
        }
        public SwitchingObjectValue(string value)
        {
            value = value.ToLower();
            if (value == "1" || value == "on" || value == "true")
                Value = true;
            else if (value == "0" || value == "off" || value == "false")
                Value = false;
            else
            {
                throw new ApplicationException("Invalid switching value");
            }
        }
        public SwitchingObjectValue(EIBBuffer buffer)
        {
            int len = buffer.data.Length;
            if (len == 2)
                m_Value = (buffer.data[1] & 0x3f) != 0;
            else
                m_Value = buffer.data[2] != 0;

        }
        #endregion

        #region Methods
        public override string ToString()
        {
            return m_Value ? "On" : "Off";
        }
        #endregion

        #region IEquatable<IValueObject> Members

        public bool Equals(IValueObject other)
        {
            SwitchingObjectValue obj = other as SwitchingObjectValue;
            if (obj != null)
                return Value.Equals(obj.Value);
            else
                return false;
        }

        #endregion

        #region IValueObject Members

        public void AdaptBufferBeforeSending(bool isWrite, EIBBuffer buffer)
        {
            buffer.data[1] = Convert.ToByte(buffer.data[1] | (m_Value ? 1 : 0));
        }

        #endregion
    }
}
